package com.example.day45.sensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

/**
 * 摇一摇
 *
 * @author zhangwei
 * @version V1.0
 * @Title: Advanced
 * @Package com.example.day45.sensor
 * @Description:
 * @date 15/10/29 上午9:47
 *
 */

public class ShakeListener implements SensorEventListener {
    private static ShakeListener utils;
    private SensorManager sensorManager;
    private final Sensor defaultSensor;
    private ShakeCallback callback;

    private ShakeListener(Context context, ShakeCallback callback) {
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        defaultSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        this.callback = callback;
    }

    public static ShakeListener getInstance(Context context, ShakeCallback callback) {
        if (utils == null) {
            utils = new ShakeListener(context, callback);
        }
        return utils;
    }

    public void registerListener() {
        sensorManager.registerListener(this, defaultSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        int x = (int) event.values[0];
        int y = (int) event.values[1];
        int z = (int) event.values[2];
        int defaultAccelerometerValue = 14;
        if (Math.abs(x) > defaultAccelerometerValue || Math.abs(y) > defaultAccelerometerValue || Math.abs(z) > defaultAccelerometerValue) {
            if (callback != null) {
                callback.onShakeCallback();
            }
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public interface ShakeCallback

    {
        void onShakeCallback();
    }

    public ShakeCallback getCallback() {
        return callback;
    }

    public void setCallback(ShakeCallback callback) {
        this.callback = callback;
    }


    public void unRegisterListener() {
        if (sensorManager != null) {
            sensorManager.unregisterListener(this);
        }

    }
}
